package com.itheima.dianming.filter;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.dianming.mapper.StuMapper;
import com.itheima.dianming.pojo.domain.Stu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;


public class UserHolderInterceptor implements HandlerInterceptor {

    @Autowired
    private StuMapper stuMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if("anonymousUser".equals(principal)){
            return true;
        }
        System.out.println(principal);
        User login =
                (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = login.getUsername();//number学号
        Stu stu = (Stu) redisTemplate.opsForValue().get(username);
        if(stu==null){
            LambdaQueryWrapper<Stu> qw = new LambdaQueryWrapper<>();
            qw.eq(Stu::getNumber,username);
            stu = stuMapper.selectOne(qw);
            redisTemplate.opsForValue().set(username,stu,5, TimeUnit.MINUTES);
        }
        UserHolder.setStu(stu);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
